package api

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-contrib/cors"
	"zhonghui/console/models"
	"zhonghui/console/service"
	"zhonghui/console/structs"
	"zhonghui/console/warehouse/envx"
	"zhonghui/console/warehouse/middlewarex"
	"zhonghui/console/warehouse/respx"

	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"gorm.io/gorm"
)

type Server struct {
	router *gin.Engine
	store  models.Store
	g      *gorm.DB
}

func NewServer(store models.Store, db *gorm.DB) *Server {
	server := &Server{store: store, g: db}
	router := gin.New()

	// pprof
	if envx.InDev() {
		pprof.Register(router)
	}
	router.Use(
		middlewarex.RequestId(),
		middlewarex.Recovery(),
		middlewarex.ExchangeLogger(true, true, nil),
		cors.New(cors.Config{
			AllowOrigins: []string{
				"http://localhost:*",
				"http://127.0.0.1:*",
				"https://uat-channelh5.pubmi.cn",
				"https://channelh5.pubmi.cn",
			},
			AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
			AllowHeaders:     []string{"DNT", "Keep-Alive", "User-Agent", "X-Requested-With", "If-Modified-Since", "Cache-Control", "Origin", "Content-Length", "Content-Type", "Authorization"},
			ExposeHeaders:    []string{"Content-Range", "Content-Length", "X-Request-ID", "Authorization"},
			AllowWildcard:    true,
			AllowCredentials: true,
			MaxAge:           24 * time.Hour,
		}),
	)

	validatorRegister()

	router.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "ok")
	})
	router.Any("health", func(c *gin.Context) {
		c.String(http.StatusOK, "ok")
	})

	// callback
	router.GET("/ping", server.Ping)
	router.GET("/data_callback", server.DataCallback)
	router.Any("/instruction_callback", server.InstructionCallback)

	authRoute := router.Group("", func(c *gin.Context) {
		user := service.GetUserFromToken(c.GetHeader("Authorization"))
		if user == nil {
			respx.UnAuth(c)
			c.Abort()
			return
		}
		c.Set(structs.UserCtx, user)
		c.Next()
	})

	// config
	authRoute.POST("/create_config", server.CreateConfig)                     // 创建配置
	authRoute.GET("/get_config_list", server.GetConfigList)                   // 获取配置列表
	authRoute.GET("/get_employee_list/:id", server.getEmployeeListByConfigId) // 跟config关联的employee
	authRoute.POST("/update_employee", server.update_employee)                // 更新用户, 欢迎语,不推送
	authRoute.POST("/update_config", server.UpdateConfig)                     // 更新配置, 重新推送
	authRoute.POST("/push_config", server.PushConfig)                         // 推送配置
	authRoute.POST("/delete_config", server.DeleteConfig)
	authRoute.GET("/get_provider_info", server.GetProviderInfo)

	// employee
	authRoute.POST("/active_employee", server.ActiveEmployee)
	authRoute.GET("/get_employee_list", server.GetEmployeeList)
	authRoute.GET("/get_active_order_list", server.GetActiveOrderList)
	authRoute.GET("/get_active_code_list", server.GetActiveCodeList)
	authRoute.GET("/get_employee_active_status", server.GetEmployeeActiveStatus)

	// mini program
	authRoute.GET("/get_mp_config_list", server.GetMpConfigList)
	authRoute.POST("/create_mp_config", server.CreateMpConfig)
	authRoute.POST("/update_mp_config", server.UpdateMpConfig)
	authRoute.GET("/get_mp_config/:config_id", server.GetMpConfigByID)

	// 导入保单
	authRoute.POST("/import-policy", server.ImportPolicy)

	// task group
	taskRoute := authRoute.Group("task")
	taskRoute.POST("/create", server.CreateTask)
	taskRoute.GET("/sms-template", server.SmsTemplate)
	taskRoute.GET("/list", server.GetTaskList)
	taskRoute.POST("/:id/start", server.StartTask)
	taskRoute.POST("/:id/pause", server.PauseTask)
	taskRoute.POST("/:id/unpause", server.UnPauseTask)
	taskRoute.POST("/:id/stop", server.StopTask)
	taskRoute.POST("/:id/test", server.TestTask)
	taskRoute.GET("/:id/charts", server.TaskCharts)
	taskRoute.GET("/charts-download", server.TaskChartsDownload)

	dashboardRoute := authRoute.Group("dashboard")
	dashboardRoute.GET("/analysis", server.GetAnalysis)

	// 入口，短信点击，跳转schema，记录转化数据
	router.GET("dwz", server.GetDwz)

	// 测试用
	router.GET("dwz-test", func(c *gin.Context) {
		sensitiveKey := service.HandleSensitiveKey(c, "18500088544", "123")

		c.String(200, fmt.Sprintf("UA：%s\nIP：%s\n省份：%s\nsk：%s",
			c.GetHeader("User-Agent"),
			c.ClientIP(),
			service.GetLocFromIP(c.ClientIP()).Province,
			sensitiveKey,
		))
	})
	// 测试用清除sensitiveKey
	router.GET("dwz-test-clear-sk", func(c *gin.Context) {
		for _, cookie := range c.Request.Cookies() {
			cookie.Expires = time.Now().Add(-time.Hour)
			c.SetCookie(cookie.Name, cookie.Value, -1, cookie.Path, cookie.Domain, cookie.Secure, cookie.HttpOnly)
		}

		c.String(200, "ok")
	})

	// H5页面内，获取小程序跳转链接
	router.GET("h5-marketing", server.GetH5Marketing)
	// 小程序内获取营销二维码或企微按钮等内容
	router.GET("mp-marketing", server.GetMpMarketing)

	router.GET("t1", func(c *gin.Context) {
		c.String(200, "{\"meta\":{\"code\":\"SUCCESS\"},\"data\":{\"visitData\":[{\"x\":\"2023-02-15\",\"y\":7},{\"x\":\"2023-02-16\",\"y\":5},{\"x\":\"2023-02-17\",\"y\":4},{\"x\":\"2023-02-18\",\"y\":2},{\"x\":\"2023-02-19\",\"y\":4},{\"x\":\"2023-02-20\",\"y\":7},{\"x\":\"2023-02-21\",\"y\":5},{\"x\":\"2023-02-22\",\"y\":6},{\"x\":\"2023-02-23\",\"y\":5},{\"x\":\"2023-02-24\",\"y\":9},{\"x\":\"2023-02-25\",\"y\":6},{\"x\":\"2023-02-26\",\"y\":3},{\"x\":\"2023-02-27\",\"y\":1},{\"x\":\"2023-02-28\",\"y\":5},{\"x\":\"2023-03-01\",\"y\":3},{\"x\":\"2023-03-02\",\"y\":6},{\"x\":\"2023-03-03\",\"y\":5}],\"visitData2\":[{\"x\":\"2023-02-15\",\"y\":1},{\"x\":\"2023-02-16\",\"y\":6},{\"x\":\"2023-02-17\",\"y\":4},{\"x\":\"2023-02-18\",\"y\":8},{\"x\":\"2023-02-19\",\"y\":3},{\"x\":\"2023-02-20\",\"y\":7},{\"x\":\"2023-02-21\",\"y\":2}],\"salesData\":[{\"x\":\"1月\",\"y\":387},{\"x\":\"2月\",\"y\":762},{\"x\":\"3月\",\"y\":642},{\"x\":\"4月\",\"y\":230},{\"x\":\"5月\",\"y\":1167},{\"x\":\"6月\",\"y\":1059},{\"x\":\"7月\",\"y\":632},{\"x\":\"8月\",\"y\":203},{\"x\":\"9月\",\"y\":274},{\"x\":\"10月\",\"y\":505},{\"x\":\"11月\",\"y\":386},{\"x\":\"12月\",\"y\":1153}],\"searchData\":[{\"index\":1,\"keyword\":\"搜索关键词-0\",\"count\":538,\"range\":68,\"status\":1},{\"index\":2,\"keyword\":\"搜索关键词-1\",\"count\":677,\"range\":97,\"status\":1},{\"index\":3,\"keyword\":\"搜索关键词-2\",\"count\":461,\"range\":58,\"status\":1},{\"index\":4,\"keyword\":\"搜索关键词-3\",\"count\":13,\"range\":57,\"status\":0},{\"index\":5,\"keyword\":\"搜索关键词-4\",\"count\":872,\"range\":20,\"status\":1},{\"index\":6,\"keyword\":\"搜索关键词-5\",\"count\":895,\"range\":12,\"status\":0},{\"index\":7,\"keyword\":\"搜索关键词-6\",\"count\":525,\"range\":50,\"status\":1},{\"index\":8,\"keyword\":\"搜索关键词-7\",\"count\":103,\"range\":13,\"status\":0},{\"index\":9,\"keyword\":\"搜索关键词-8\",\"count\":18,\"range\":69,\"status\":0},{\"index\":10,\"keyword\":\"搜索关键词-9\",\"count\":612,\"range\":67,\"status\":1},{\"index\":11,\"keyword\":\"搜索关键词-10\",\"count\":567,\"range\":14,\"status\":0},{\"index\":12,\"keyword\":\"搜索关键词-11\",\"count\":64,\"range\":59,\"status\":0},{\"index\":13,\"keyword\":\"搜索关键词-12\",\"count\":732,\"range\":76,\"status\":0},{\"index\":14,\"keyword\":\"搜索关键词-13\",\"count\":703,\"range\":91,\"status\":0},{\"index\":15,\"keyword\":\"搜索关键词-14\",\"count\":329,\"range\":28,\"status\":1},{\"index\":16,\"keyword\":\"搜索关键词-15\",\"count\":250,\"range\":76,\"status\":1},{\"index\":17,\"keyword\":\"搜索关键词-16\",\"count\":439,\"range\":93,\"status\":1},{\"index\":18,\"keyword\":\"搜索关键词-17\",\"count\":674,\"range\":43,\"status\":0},{\"index\":19,\"keyword\":\"搜索关键词-18\",\"count\":591,\"range\":94,\"status\":1},{\"index\":20,\"keyword\":\"搜索关键词-19\",\"count\":172,\"range\":43,\"status\":1},{\"index\":21,\"keyword\":\"搜索关键词-20\",\"count\":464,\"range\":56,\"status\":0},{\"index\":22,\"keyword\":\"搜索关键词-21\",\"count\":794,\"range\":31,\"status\":1},{\"index\":23,\"keyword\":\"搜索关键词-22\",\"count\":82,\"range\":48,\"status\":1},{\"index\":24,\"keyword\":\"搜索关键词-23\",\"count\":33,\"range\":97,\"status\":0},{\"index\":25,\"keyword\":\"搜索关键词-24\",\"count\":391,\"range\":50,\"status\":0},{\"index\":26,\"keyword\":\"搜索关键词-25\",\"count\":756,\"range\":27,\"status\":1},{\"index\":27,\"keyword\":\"搜索关键词-26\",\"count\":692,\"range\":36,\"status\":0},{\"index\":28,\"keyword\":\"搜索关键词-27\",\"count\":42,\"range\":28,\"status\":1},{\"index\":29,\"keyword\":\"搜索关键词-28\",\"count\":927,\"range\":92,\"status\":1},{\"index\":30,\"keyword\":\"搜索关键词-29\",\"count\":306,\"range\":60,\"status\":1},{\"index\":31,\"keyword\":\"搜索关键词-30\",\"count\":345,\"range\":18,\"status\":1},{\"index\":32,\"keyword\":\"搜索关键词-31\",\"count\":429,\"range\":65,\"status\":0},{\"index\":33,\"keyword\":\"搜索关键词-32\",\"count\":173,\"range\":44,\"status\":1},{\"index\":34,\"keyword\":\"搜索关键词-33\",\"count\":387,\"range\":40,\"status\":1},{\"index\":35,\"keyword\":\"搜索关键词-34\",\"count\":966,\"range\":16,\"status\":0},{\"index\":36,\"keyword\":\"搜索关键词-35\",\"count\":257,\"range\":58,\"status\":0},{\"index\":37,\"keyword\":\"搜索关键词-36\",\"count\":408,\"range\":50,\"status\":0},{\"index\":38,\"keyword\":\"搜索关键词-37\",\"count\":827,\"range\":92,\"status\":1},{\"index\":39,\"keyword\":\"搜索关键词-38\",\"count\":694,\"range\":29,\"status\":1},{\"index\":40,\"keyword\":\"搜索关键词-39\",\"count\":369,\"range\":2,\"status\":0},{\"index\":41,\"keyword\":\"搜索关键词-40\",\"count\":658,\"range\":62,\"status\":1},{\"index\":42,\"keyword\":\"搜索关键词-41\",\"count\":923,\"range\":1,\"status\":0},{\"index\":43,\"keyword\":\"搜索关键词-42\",\"count\":216,\"range\":22,\"status\":1},{\"index\":44,\"keyword\":\"搜索关键词-43\",\"count\":499,\"range\":84,\"status\":1},{\"index\":45,\"keyword\":\"搜索关键词-44\",\"count\":796,\"range\":50,\"status\":1},{\"index\":46,\"keyword\":\"搜索关键词-45\",\"count\":29,\"range\":42,\"status\":1},{\"index\":47,\"keyword\":\"搜索关键词-46\",\"count\":266,\"range\":3,\"status\":0},{\"index\":48,\"keyword\":\"搜索关键词-47\",\"count\":906,\"range\":26,\"status\":1},{\"index\":49,\"keyword\":\"搜索关键词-48\",\"count\":975,\"range\":64,\"status\":0},{\"index\":50,\"keyword\":\"搜索关键词-49\",\"count\":104,\"range\":53,\"status\":1}],\"offlineData\":[{\"name\":\"Stores 0\",\"cvr\":0.5},{\"name\":\"Stores 1\",\"cvr\":0.3},{\"name\":\"Stores 2\",\"cvr\":0.7},{\"name\":\"Stores 3\",\"cvr\":0.7},{\"name\":\"Stores 4\",\"cvr\":0.4},{\"name\":\"Stores 5\",\"cvr\":0.1},{\"name\":\"Stores 6\",\"cvr\":0.5},{\"name\":\"Stores 7\",\"cvr\":0.2},{\"name\":\"Stores 8\",\"cvr\":0.8},{\"name\":\"Stores 9\",\"cvr\":0.3}],\"offlineChartData\":[{\"date\":\"13:31\",\"type\":\"客流量\",\"value\":79},{\"date\":\"13:31\",\"type\":\"支付笔数\",\"value\":93},{\"date\":\"14:01\",\"type\":\"客流量\",\"value\":108},{\"date\":\"14:01\",\"type\":\"支付笔数\",\"value\":105},{\"date\":\"14:31\",\"type\":\"客流量\",\"value\":69},{\"date\":\"14:31\",\"type\":\"支付笔数\",\"value\":31},{\"date\":\"15:01\",\"type\":\"客流量\",\"value\":107},{\"date\":\"15:01\",\"type\":\"支付笔数\",\"value\":60},{\"date\":\"15:31\",\"type\":\"客流量\",\"value\":99},{\"date\":\"15:31\",\"type\":\"支付笔数\",\"value\":94},{\"date\":\"16:01\",\"type\":\"客流量\",\"value\":33},{\"date\":\"16:01\",\"type\":\"支付笔数\",\"value\":53},{\"date\":\"16:31\",\"type\":\"客流量\",\"value\":24},{\"date\":\"16:31\",\"type\":\"支付笔数\",\"value\":63},{\"date\":\"17:01\",\"type\":\"客流量\",\"value\":82},{\"date\":\"17:01\",\"type\":\"支付笔数\",\"value\":55},{\"date\":\"17:31\",\"type\":\"客流量\",\"value\":48},{\"date\":\"17:31\",\"type\":\"支付笔数\",\"value\":38},{\"date\":\"18:01\",\"type\":\"客流量\",\"value\":78},{\"date\":\"18:01\",\"type\":\"支付笔数\",\"value\":17},{\"date\":\"18:31\",\"type\":\"客流量\",\"value\":63},{\"date\":\"18:31\",\"type\":\"支付笔数\",\"value\":102},{\"date\":\"19:01\",\"type\":\"客流量\",\"value\":91},{\"date\":\"19:01\",\"type\":\"支付笔数\",\"value\":74},{\"date\":\"19:31\",\"type\":\"客流量\",\"value\":16},{\"date\":\"19:31\",\"type\":\"支付笔数\",\"value\":54},{\"date\":\"20:01\",\"type\":\"客流量\",\"value\":105},{\"date\":\"20:01\",\"type\":\"支付笔数\",\"value\":95},{\"date\":\"20:31\",\"type\":\"客流量\",\"value\":41},{\"date\":\"20:31\",\"type\":\"支付笔数\",\"value\":39},{\"date\":\"21:01\",\"type\":\"客流量\",\"value\":74},{\"date\":\"21:01\",\"type\":\"支付笔数\",\"value\":22},{\"date\":\"21:31\",\"type\":\"客流量\",\"value\":28},{\"date\":\"21:31\",\"type\":\"支付笔数\",\"value\":16},{\"date\":\"22:01\",\"type\":\"客流量\",\"value\":69},{\"date\":\"22:01\",\"type\":\"支付笔数\",\"value\":101},{\"date\":\"22:31\",\"type\":\"客流量\",\"value\":105},{\"date\":\"22:31\",\"type\":\"支付笔数\",\"value\":60},{\"date\":\"23:01\",\"type\":\"客流量\",\"value\":41},{\"date\":\"23:01\",\"type\":\"支付笔数\",\"value\":96}],\"salesTypeData\":[{\"x\":\"家用电器\",\"y\":4544},{\"x\":\"食用酒水\",\"y\":3321},{\"x\":\"个护健康\",\"y\":3113},{\"x\":\"服饰箱包\",\"y\":2341},{\"x\":\"母婴产品\",\"y\":1231},{\"x\":\"其他\",\"y\":1231}],\"salesTypeDataOnline\":[{\"x\":\"家用电器\",\"y\":244},{\"x\":\"食用酒水\",\"y\":321},{\"x\":\"个护健康\",\"y\":311},{\"x\":\"服饰箱包\",\"y\":41},{\"x\":\"母婴产品\",\"y\":121},{\"x\":\"其他\",\"y\":111}],\"salesTypeDataOffline\":[{\"x\":\"家用电器\",\"y\":99},{\"x\":\"食用酒水\",\"y\":188},{\"x\":\"个护健康\",\"y\":344},{\"x\":\"服饰箱包\",\"y\":255},{\"x\":\"其他\",\"y\":65}],\"radarData\":[{\"name\":\"个人\",\"label\":\"引用\",\"value\":10},{\"name\":\"个人\",\"label\":\"口碑\",\"value\":8},{\"name\":\"个人\",\"label\":\"产量\",\"value\":4},{\"name\":\"个人\",\"label\":\"贡献\",\"value\":5},{\"name\":\"个人\",\"label\":\"热度\",\"value\":7},{\"name\":\"团队\",\"label\":\"引用\",\"value\":3},{\"name\":\"团队\",\"label\":\"口碑\",\"value\":9},{\"name\":\"团队\",\"label\":\"产量\",\"value\":6},{\"name\":\"团队\",\"label\":\"贡献\",\"value\":3},{\"name\":\"团队\",\"label\":\"热度\",\"value\":1},{\"name\":\"部门\",\"label\":\"引用\",\"value\":4},{\"name\":\"部门\",\"label\":\"口碑\",\"value\":1},{\"name\":\"部门\",\"label\":\"产量\",\"value\":6},{\"name\":\"部门\",\"label\":\"贡献\",\"value\":5},{\"name\":\"部门\",\"label\":\"热度\",\"value\":7}]}}")
	})

	// 上传
	router.POST("upload", server.Upload)

	// 手机号登入或绑定手机
	router.POST("sign-in", server.PostSignIn)
	// 绑定微信
	router.POST("bind", server.PostBind)
	// 获取带掩码的用户信息
	router.GET("user", server.GetUser)

	// 获取管理员列表
	router.GET("users", server.GetUsers)
	// 创建管理员
	router.POST("users", server.PostUsers)
	// 编辑管理员
	router.PUT("users/:id", server.PutUsers)

	// 获取用户组列表
	router.GET("groups", server.GetGroups)
	// 创建管理员组
	router.POST("groups", server.PostGroups)
	// 创建管理员组
	router.DELETE("groups/:id", server.DeleteGroups)
	// 获取组内成员
	router.GET("groups/:id/users", server.GetGroupsUsers)
	// 配置组成员
	router.POST("groups/:id/users", server.PostGroupsMembers)

	// 获取策略列表
	router.GET("policies", server.GetPolicies)
	// 获取当前用户或组拥有的权限
	router.GET("permissions", server.GetPermissions)
	// 修改权限
	router.PUT("permissions", server.PutPermissions)

	// oss上传凭证
	router.GET("oss-ticket", server.Sts)
	// oss签名直传
	router.POST("oss-sign", server.Sign)

	server.router = router
	return server
}

func (server *Server) Start(addr string) error {
	return server.router.Run(addr)
}

func validatorRegister() {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("smsChannel", func(fl validator.FieldLevel) bool {
			if smsChannel, ok := fl.Field().Interface().(string); ok {
				if smsChannel == "aliyun" || smsChannel == "tencent" {
					return true
				}
			}
			return false
		})
	}
}
